﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Drawing;

namespace Lyh.MyQQListView.Util
{
    /// <summary>
    /// 鼠标操作帮助类
    /// </summary>
    public class MouseHelper
    {
        [DllImport("User32")]
        public extern static void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo);

        [DllImport("User32")]
        public extern static void SetCursorPos(int x, int y);

        [DllImport("User32")]
        public extern static bool GetCursorPos(out POINT p);

        [StructLayout(LayoutKind.Sequential)]
        public struct POINT
        {
            public int X;
            public int Y;
        }

        public enum MouseEventFlags
        {
            Move = 0x0001,
            LeftDown = 0x0002,
            LeftUp = 0x0004,
            RightDown = 0x0008,
            RightUp = 0x0010,
            MiddleDown = 0x0020,
            MiddleUp = 0x0040,
            Wheel = 0x0800,
            Absolute = 0x8000
        }

        /// <summary>
        /// 单击指定坐标位置
        /// </summary>
        /// <param name="x">相对于屏幕的X坐标</param>
        /// <param name="y">相对于屏幕的Y坐标</param>
        public static void AutoClick(int x, int y)
        {
            POINT p = new POINT();
            GetCursorPos(out p);
            try
            {
                SetCursorPos(x, y);
                mouse_event((int)(MouseEventFlags.LeftDown | MouseEventFlags.Absolute), 0, 0, 0, IntPtr.Zero);
                mouse_event((int)(MouseEventFlags.LeftUp | MouseEventFlags.Absolute), 0, 0, 0, IntPtr.Zero);
            }
            finally
            {
                SetCursorPos(p.X, p.Y);
            }
        }

        /// <summary>
        /// 自动单击控件
        /// </summary>
        /// <param name="ctr">控件</param>
        public static void AutoClick(Control ctr)
        {
            Point p = ctr.PointToScreen(new Point(0, 0));
            AutoClick(p.X + ctr.Width / 2, p.Y + ctr.Height / 2);
        }
    }
}